package com.jwthhealth_pub.old.report.view;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bm.library.PhotoView;
import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.base.BaseActivity;
import com.jwthhealth_pub.common.view.TitleLayout;
import com.jwthhealth_pub.old.common.ImageLoader;
import com.jwthhealth_pub.old.report.model.resbody.HraDataRes;
import com.jwthhealth_pub.old.report.view.adapter.PhyStatAdapter;
import com.jwthhealth_pub.old.report.view.adapter.ReportPhisicalAdapter;
import com.jwthhealth_pub.old.report.view.widget.Jwth_CircleProgressbar;
import com.jwthhealth_pub.old.report.view.widget.LikeDialog;
import com.jwthhealth_pub.old.report.view.widget.LikeLinearlayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import uk.co.senab.photoview.PhotoViewAttacher;


public class ReportPhysicalActivity extends BaseActivity {
    @BindView(R.id.body_title)
    TextView bodyTitle;
    @BindView(R.id.temp_img)
    ImageView tempImg;
    @BindView(R.id.temp_bg_layout)
    RelativeLayout tempBgLayout;
    @BindView(R.id.rv_stataus)
    RecyclerView rvStataus;
    @BindView(R.id.title_desc)
    TextView titleDesc;
    @BindView(R.id.img1)
    PhotoView mImg1;
    @BindView(R.id.img2)
    PhotoView mImg2;
    private ImageView headIv;
    private Jwth_CircleProgressbar mCircleProgressbar;
    private RecyclerView valuesRv;
    private int mScoreProgressbar = 0;
    private HraDataRes.DataBean.ZjBean.SonBeanX mData;
    private TextView describeTv, describeTitleTv;
    private List<HraDataRes.DataBean.ZjBean.SonBeanX.SonBean> mSon;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_reprot_environment_detail);
        ButterKnife.bind(this);
        headIv = findViewById(R.id.iv_head);
        mCircleProgressbar = findViewById(R.id.circleProgress);
        valuesRv = findViewById(R.id.rv_values);
        describeTv = findViewById(R.id.tv_status);
        describeTitleTv = findViewById(R.id.tv_status_title);

        getData();

    }

    @Override
    protected void title() {

        TitleLayout titleLayout = findViewById(R.id.title_layout);

        if (mData.getHra_type() != null) titleLayout.setTitle(mData.getHra_type());

        titleLayout.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
                finish();
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {

            }

            @Override
            public void rightTextClick() {

            }
        });

        if (mData != null && mData.getPercent() != null && mData.getBelow() != null && mData.getTotal() != null)
            titleDesc.setText("本系统测试项共" + mData.getTotal() + "项, 您超出范围的有" + mData.getBelow() + "项,占" + mData.getPercent());
    }

    public void getData() {
        mData = getIntent().getParcelableExtra("data");
        if (mData == null) return;
        refresh();

        showScaleImg(mData.getPic());
    }

    private void refresh() {
        ImageLoader.picasso(mData.getPic(), headIv);
        showCircleProgressbar(Float.parseFloat(mData.getScore()));
        CustomLinearLayoutManager customLinearLayoutManager = new CustomLinearLayoutManager(this);
//        valuesRv.setLayoutManager(new LinearLayoutManager(this));
//        valuesRv.setLayoutManager(customLinearLayoutManager);
        valuesRv.setLayoutManager(new LikeLinearlayout(this));
        mSon = mData.getSon();
        if (mSon.size() < 5) {
            showAllData();
        } else {
            showPreviewData();
        }
//        valuesRv.setNestedScrollingEnabled(false);

        describeTitleTv.setText(mData.getZt_name());
        bodyTitle.setMaxEms(7);
        bodyTitle.setText(mData.getHra_type() + "当前得分");


        //状态列表
//        String describe = mData.getShuoming().replace("EOF", "\r\n");
//        describeTv.setText(describe);
//
//        Log.d("ReportPhysicalActivity", describe);
        rvStataus.setLayoutManager(new LinearLayoutManager(this));
        rvStataus.setAdapter(new PhyStatAdapter(this, mData.getHra_type(), mData.getShuoming()));
    }

    public void showPreviewData() {
        if (mSon == null) return;
        List<HraDataRes.DataBean.ZjBean.SonBeanX.SonBean> _son = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            _son.add(mSon.get(i));
        }
        valuesRv.setAdapter(new ReportPhisicalAdapter(this, _son, mData.getId()));
    }

    public void showAllData() {
        if (mSon == null) return;
        valuesRv.setAdapter(new ReportPhisicalAdapter(this, mSon, mData.getId()));
    }

    public void showCircleProgressbar(float score) {
//        final Float progessbar = (float) score / 100 * 360;
//        float _progressbarr = progessbar;
        mCircleProgressbar.setProgressbar((int) (score / 100 * 220), score);
//        Observable.interval(20, TimeUnit.MILLISECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
////                .takeWhile(mScoreProgressbar -> mScoreProgressbar <= progessbar)//下面的回调每加一调用两次，所以这里的值缩小1/2
//                .takeWhile(new Predicate<Long>() {
//                    @Override
//                    public boolean test(@NonNull Long aLong) throws Exception {
//                        return mScoreProgressbar <= progessbar;
//                    }
//                })
//                .map(new Function<Long, String>() {
//                    @Override
//                    public String apply(@NonNull Long aLong) throws Exception {
//                        mScoreProgressbar++;
//                        if (mScoreProgressbar <= progessbar) {
//                            mCircleProgressbar.setProgressbar(mScoreProgressbar);
//                        }
//                        return String.valueOf(mScoreProgressbar);
//                    }
//                }).subscribe(new Observer<String>() {
//            @Override
//            public void onSubscribe(@NonNull Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(@NonNull String s) {
////                Log.d("ReportContentFragment", "s:" + s);
//            }
//
//            @Override
//            public void onError(@NonNull Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
    }

//    @OnClick(R.id.click_zoom_layout)
    @OnClick(R.id.img1)
    public void onViewClicked() {
        showImageDialog();
        showScaleImg(mData.getPic());
        String picUrl = mData.getPic();


        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(R.layout.item_zoom);
        View view = View.inflate(this, R.layout.item_zoom, null);
        PhotoView ivPhoto = view.findViewById(R.id.iv_photo);
        ImageView closeBtn = view.findViewById(R.id.btn_close);
        ImageLoader.picasso(picUrl, ivPhoto);

        PhotoViewAttacher attacher = new PhotoViewAttacher(ivPhoto);

        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        attacher.setScale(attacher.getMaximumScale(), width / 2, height / 2, true);
        attacher.update();


        builder.setView(view);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });


    }

    private void showScaleImg(String pic) {
        //设置不可以双指缩放移动放大等操作，跟普通的image一模一样,默认情况下就是disenable()状态
        ImageLoader.picasso(pic, mImg1);
        ImageLoader.picasso(pic, mImg2);

        mImg1.disenable();
        mImg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消标题栏
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                tempBgLayout.setBackgroundResource(R.mipmap.bg_subscribe_title);
                mImg2.setVisibility(View.VISIBLE);
            }
        });

        // 需要启动缩放需要手动开启
        mImg2.enable();
        mImg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getWindow().clearFlags(
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                tempBgLayout.setBackgroundColor(ContextCompat.getColor(ReportPhysicalActivity.this, R.color.transparency));
                mImg2.setVisibility(View.GONE);
            }
        });
    }

    private class CustomLinearLayoutManager extends LinearLayoutManager {
        private boolean isScrollEnabled = true;

        CustomLinearLayoutManager(Context context) {
            super(context);
        }

        @Override
        public boolean canScrollVertically() {
            //Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
            return isScrollEnabled && super.canScrollVertically();
        }
    }

    private void showImageDialog() {
        if (mData == null || mData.getPic() == null) return;
        String picUrl = mData.getPic();
        View view = getLayoutInflater().inflate(R.layout.item_zoom, null);
        ImageView closeBtn = view.findViewById(R.id.btn_close);


        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        int width = dm.widthPixels;
        int height = dm.heightPixels;

        final LikeDialog builder = new LikeDialog(this, width - 20, height - 320, view, R.style.dialog);
        builder.show();

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builder.dismiss();
            }
        });
    }
}
